package com.doit.day05

import scala.collection.immutable
import scala.io.Source

object _01_电影 {
  def main(args: Array[String]): Unit = {
    val ratings: List[String] = Source.fromFile("C:\\Users\\yi\\Desktop\\课程资料\\资料\\ratings.txt").getLines().toList
    val movies: List[String] = Source.fromFile("C:\\Users\\yi\\Desktop\\课程资料\\资料\\movies.txt").getLines().toList

    //怎么将一对一的关系，变成1对多的关系
    val id_Type: List[(String, List[String])] = movies.map(line => {
      //1_Toy Story (1995)_Animation|Children's|Comedy
      val arr: Array[String] = line.split("_")
      val movie_id: String = arr(0)
      val list: List[String] = arr(2).split("\\|").toList
      (movie_id,list)
    })

    val idAndRatings: Map[String, List[Double]] = ratings.map(line => {
      val arr: Array[String] = line.split("_")
      //电影id，分数
      (arr(1), arr(2))
    }).groupBy(_._1)
      .map(tp=>{
        val movie_id: String = tp._1
        //电影id，分数的集合
        (movie_id,tp._2.map(_._2.toDouble))
      })

    //将电影id转换成电影的类型  ==》 想要得到的是什么？电影类型(List)和分数
  /*  val iterable: List[(String, Double)] = idAndRatings.map(tp => {
      val movie_id: String = tp._1
      //获取电影类型的集合
      val typeList: List[String] = id_Type.toMap.getOrElse(movie_id, List("不认识"))
      val ratings: List[Double] = tp._2
      //elem 是每一个电影的类型
      val res: List[List[(String, Double)]] = for (elem <- typeList) yield {
        for (elem1 <- ratings) yield {
          (elem, elem1)
        }
      }
      res
    }).toList.flatten.flatten

    iterable.groupBy(_._1)
      .map(tp=>{
        (tp._1,(tp._2.map(_._2).sum/tp._2.size).formatted("%.3f").toDouble)
      }).toList
      .sortBy(-_._2)
      .take(3)
      .foreach(println)*/

    //方法二
    val map: Map[String, List[String]] = movies.map(line => {
      val arr: Array[String] = line.split("_")
      val arr1: Array[String] = arr(2).split("\\|")
      for (elem <- arr1) yield {
        (arr(0), elem)
      }
    }).flatten
      .groupBy(_._2) //Map[电影类型，List[(电影id，电影类型)]]
      .map(tp => {
        (tp._1, tp._2.map(_._1)) //Map[电影类型，List[电影id]]
      }).toMap

    val id_rating: Map[String, List[Double]] = ratings.map(line => {
      val arr: Array[String] = line.split("_")
      //      1_1193_5_978300760
      val movie_id: String = arr(1)
      val rating: String = arr(2)
      (movie_id, rating)
    }).groupBy(_._1)
      .map(tp=>{
        (tp._1,tp._2.map(_._2.toDouble))
      })

    map.map(tp=>{
      val movie_type: String = tp._1
      val movie_ids: List[String] = tp._2
      val list: List[List[Double]] = for (elem <- movie_ids) yield{
        id_rating.getOrElse(elem, List(0.0))
      }
      val flatten: List[Double] = list.flatten
      (movie_type,(flatten.sum/flatten.size).formatted("%.3f").toDouble)
    }).toList
      .sortBy(-_._2)
      .take(3)
      .foreach(println)







  }
}
